package viewer;

import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

import model.ShareFileModel;
import operate.LocalClientOperate;
import client.LocalClient;

import common.Client;
import common.ClientOperate;

public class ClientFrame extends JFrame implements WindowListener, ActionListener {

	private static final long serialVersionUID = -2581627007886303308L;
	private String serverAdd = Client.rb.getString("server-address");
	private String serverPort = Client.rb.getString("server-port");
	Client client;
	ClientOperate operate;
	
	public JLabel serverAddressLbl = new JLabel("服务器ip地址:");
	public JTextField serverAddressTxt = new JTextField(15);
	public JLabel serverPortLbl = new JLabel("服务器端口:");
	public JTextField serverPortTxt = new JTextField(7);
	public JButton linkServerBtn = new JButton("连接");
	
	public JLabel shareFileLbl = new JLabel("服务器共享文件:");
	public JComboBox shareFileCb = new JComboBox();
	public JButton openFileBth = new JButton("打开");
	public JButton freshenBtn = new JButton("刷新");
	public JButton clearBtn = new JButton("clear");
	public JButton closeBtn = new JButton("关闭");
	
	public JTextArea readFileArea = new JTextArea(40, 80);
	public JScrollPane scrollPane = new JScrollPane(readFileArea);
	
	public ClientFrame() {
		
		init();
		createEvent();
	}
	
	private void createEvent() {
		
		linkServerBtn.addActionListener(this);
		openFileBth.addActionListener(this);
		freshenBtn.addActionListener(this);
		clearBtn.addActionListener(this);
		closeBtn.addActionListener(this);
	}
	
	private void init() {
		
		readFileArea.setEditable(false);
		scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
		scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
		shareFileCb.insertItemAt("请先连接服务器", 0);
		
		Container currFrame = this.getContentPane();
		currFrame.setLayout(new FlowLayout());
		currFrame.add(serverAddressLbl);
		serverAddressTxt.setText(serverAdd);
		currFrame.add(serverAddressTxt);
		currFrame.add(serverPortLbl);
		serverPortTxt.setText(serverPort);
		currFrame.add(serverPortTxt);
		currFrame.add(linkServerBtn);
		currFrame.add(shareFileLbl);
		currFrame.add(shareFileCb);
		currFrame.add(openFileBth);
		currFrame.add(freshenBtn);
		currFrame.add(clearBtn);
		currFrame.add(closeBtn);
		currFrame.add(scrollPane);
		
		this.setSize(700, 500);
		this.setTitle("Log Client");
		this.setDefaultCloseOperation(3);
		this.setEnabled(true);
		this.setVisible(true);
	}
	

	@Override
	public void windowActivated(WindowEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void windowClosed(WindowEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void windowClosing(WindowEvent arg0) {
		
		closeWindow();
	}

	@Override
	public void windowDeactivated(WindowEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void windowDeiconified(WindowEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void windowIconified(WindowEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void windowOpened(WindowEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void actionPerformed(ActionEvent event) {
		
		Object btnObj = event.getSource();
		if (btnObj.equals(linkServerBtn)) {
			client = new LocalClient(serverAddressTxt.getText(), Integer.parseInt(serverPortTxt.getText()));
			operate = new LocalClientOperate(client, this);
			operate.connect();
			shareFileCb.removeAllItems();
			for (ShareFileModel file : client.getListShareFile()) {
				shareFileCb.insertItemAt(file.getFileName(), 0);
			}
		}
		if (btnObj.equals(openFileBth)) {
			if (client != null) {
				boolean off = shareFileCb.getSelectedItem().toString().equals(client.getFileName());// 是否在读现在已经读取了的文件
				if (!off) {
					readFileArea.setText("");
				} else {
					int opt = JOptionPane.showConfirmDialog(this, "是否清空阅读区?(清空后只显示最新内容)", "Warning", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.INFORMATION_MESSAGE);
					if (opt == JOptionPane.YES_OPTION) {
						readFileArea.setText("");
					}
				}
				operate.getFile(shareFileCb.getSelectedItem().toString(), off);
			} else {
				JOptionPane.showMessageDialog(this, "请先连接服务器");
			}
		}
		if (btnObj.equals(freshenBtn)) {
			
			if (client != null) {
				operate.getListShareFile();
				shareFileCb.removeAllItems();
				for (ShareFileModel file : client.getListShareFile()) {
					shareFileCb.insertItemAt(file.getFileName(), 1);
				}
			} else {
				JOptionPane.showMessageDialog(this, "请先连接服务器");
			}
		}
		if (btnObj.equals(clearBtn)) {
			readFileArea.setText("");
		}
		if (btnObj.equals(closeBtn)) {
			closeWindow();
		}
	}
	
	/**
	 * 提供给更新文件通知线程,把更新的文件内容刷新到阅读区域.
	 * 
	 * @param file
	 */
	public void appendUpFileToReadArea(File file) {
		
		try {
			RandomAccessFile fileIn = new RandomAccessFile(file, "r");
			// 定位到开始读取到的位子
			String print = "";
			while ((print = fileIn.readLine()) != null) {
				readFileArea.append(print + "\12");
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	private void closeWindow() {
		
		try {
			int opt = JOptionPane.showConfirmDialog(this, "Exit ?", "Warning", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.INFORMATION_MESSAGE);
			if (opt == JOptionPane.YES_OPTION) {
				if (client == null && null == operate) {
					System.exit(0);
				}
				operate.sendLogout();
				System.exit(0);
				System.out.println("Client log out!");
			}
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("ERROR:Client log out!");
			System.exit(0);
		}
	}

}
